<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>秦峰预制厂进销存</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="js-lib/ext-js/resources/css/ext-all.css">
</head>

<body>
<div id="x-loading-mask" style="width:100%; height:100%; background:#618BAC; position:absolute; z-index:20000; left:0; top:0;">&#160;</div>
  <div id="x-loading-panel" style="position:absolute;left:40%;top:40%;border:1px solid #9c9f9d;padding:2px;background:#d1d8db;width:300px;text-align:center;z-index:20001;">
    <div style="border:1px solid #c1d1d6;color:#666;background:white;padding:10px;margin:0;padding-left: 20px;height:30px;text-align:left;">
      <div id="load-status" style="height:30px;padding-top:5px;">载入中...</div>
    </div>
</div>
<script type="text/javascript" src="js-lib/ext-js/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="js-lib/ext-js/ext-all.js"></script>
<script type="text/javascript" src="js-lib/ext-ux-js/CheckboxField.js"></script>
<script type="text/javascript" src="js-lib/ext-ux-js/RowExpander.js"></script>
<script type="text/javascript" src="js-lib/ext-ux-js/GroupSummary.js"></script>



<script type="text/javascript" src="js-lib/ext-ux-js/RowEditor.js"></script>
<script type="text/javascript" src="js-lib/ext-ux-js/xtprinter/extjs_printergrid_0.0.1.js"></script>

<script type="text/javascript" src="js-lib/ext-ux-js/TabCloseMenu.js"></script>
<link rel="stylesheet" type="text/css" href="js-lib/ext-ux-js/resources/css/Spinner.css">
<link rel="stylesheet" type="text/css" href="js-lib/ext-ux-js/resources/css/grid-examples.css">
<link rel="stylesheet" type="text/css" href="js-lib/ext-ux-js/resources/css/CheckboxField.css">
 <link rel="stylesheet" type="text/css" href="js-lib/ext-ux-js/resources/css/RowEditor.css">
 <link rel="stylesheet" type="text/css" href="js-lib/ext-ux-js/resources/css/GroupSummary.css">
 
 
	<script type='text/javascript' src='dwr/engine.js'></script>
	<script type='text/javascript' src='dwr/util.js'></script> 
	<script type='text/javascript' src='dwr/interface/PartyManager.js'></script> 
	<script type='text/javascript' src='dwr/interface/ProductManager.js'></script> 
	<script type='text/javascript' src='dwr/interface/SaleManager.js'></script> 
	<script type='text/javascript' src='dwr/interface/DBTool.js'></script> 
	<script type='text/javascript' src='dwr/interface/TrackingNumberGenerator.js'></script>

	<script type="text/javascript" src="js-lib/ext-ux-js/avatar.js"></script>
<style type="text/css">
.main-header .x-panel-body {
    background:transparent;
}

</style>
<script type="text/javascript">
Ext.BLANK_IMAGE_URL = "js-lib/ext-js/resources/images/default/s.gif";

Ext.ns('avatar.security.framework');

var global_printer = null;  // it has to be on the index page or the generator page  always 
function printmygridGO(obj){  global_printer.printGrid(obj);	} 
function printmygridGOcustom(obj){ global_printer.printCustom(obj);	}  	

avatar.security.framework.HeaderPanel = Ext.extend(Ext.Panel, {
    
    initComponent:function() {
        Ext.apply(this, {
            border :false,
            layout :'anchor',
            region :'north',
            cls: 'main-header',
            height :30,
            items:[
			/**{
                xtype :'box',
                border :false,
                el: 'header',
                height :30
            }, */
            new Ext.Toolbar( {
                border:true,
                items : [
				{ text: '数据导出', iconCls: 'export',handler:
				  function(){
					  DBTool.export2sql(function(filename){
                         Ext.MessageBox.alert("信息", "成功导出到文件 " + filename);
					  });

				  }
				
				}, 
				{ text: '数据导入', iconCls: 'import',handler:
				  function(){
					  DBTool.importLatestData(function(filename){
                          if (filename == ''){
                             Ext.MessageBox.alert('信息', '未在备份目录中发现sql文件.');
                          } else
							  Ext.MessageBox.alert('信息', '已成功导入 ' + filename); 
					  });

				  }
				
				}, 
                '->',
				{
                    text: '产品与库存',
                    iconCls :'stock',
                    handler : function() {
                        mainPanel.loadModule('modules/product.js', 'products');
                    }
                },
				
				{
                    text:'帐目用户',
                    iconCls :'user',
                    handler : function() {
                        mainPanel.loadModule('modules/accountingusers.js', 'accounting_users');
                    }
                }]
            })
            ]
        }); // eo apply
        avatar.security.framework.HeaderPanel.superclass.initComponent.apply(this, arguments);
    } // eo function initComponent
}); // eo Tutorial.LocalizationWin


var salesman_ds = new Ext.data.JsonStore({fields : ["id", "name"]}),			
	carrier_ds = new Ext.data.JsonStore({fields : ["id", "name"]}),
	maker_ds = new Ext.data.JsonStore({fields : ["id", "name"]});

salesman_ds.on('load', function(store) {
	store.insert(0, new Ext.data.Record({id: '-1', name: ''}) );
});
maker_ds.on('load', function(store) {
	store.insert(0, new Ext.data.Record({id: '-1', name: ''}) );
});
carrier_ds.on('load', function(store) {
	store.insert(0, new Ext.data.Record({id: '-1', name: ''}) );
});

PartyManager.getAllActivePartyByRole('maker', function(data){
	maker_ds.loadData(data);
});
PartyManager.getAllActivePartyByRole('salesman', function(data){
	salesman_ds.loadData(data);
});
PartyManager.getAllActivePartyByRole('carrier', function(data){
	carrier_ds.loadData(data);
});

MenuTreePanel = function() {

    // 显式调用父类构造器    
    MenuTreePanel.superclass.constructor.call(this, {
        id:'module-tree',
		labelWidth: 56, 
		region:'center',
		//labelAlign: 'top',
		frame: true,
		defaults: {anchor: '99%'},
		defaultType: 'textfield',
		items: [
			 {
				xtype: 'combo',
				fieldLabel: '类型',
				id : 'search-type',
				store: ['销售单','生产单','产品销售统计','货运单'],
				forceSelection : true,
				displayField: 'name',
				valueField:'id',
				editable: false,
				typeAhead: true,
				mode: 'local',
				value : '销售单',
				triggerAction: 'all',
				selectOnFocus:true,
				setFieldVisible: function(cmp, visible){
					cmp.setVisible(visible);
					if (visible)
					{
						cmp.enable();
                        cmp.getEl().up('.x-form-item').setDisplayed(true); 
					} else {
                        cmp.disable();
                        cmp.getEl().up('.x-form-item').setDisplayed(false); 
 
					}
				},
                listeners : {
				   'select' : function(combo, rec, index){
					   this.setFieldVisible( Ext.getCmp('sale-search-customer'), index == 0);
					   this.setFieldVisible( Ext.getCmp('sale-search-carrier'), index == 0 || index == 3);
					   this.setFieldVisible( Ext.getCmp('warehousing-search-maker'), index == 1);
					   this.setFieldVisible( Ext.getCmp('sale-search-saler'), index == 0);
					   this.setFieldVisible( Ext.getCmp('sale-search-state'), index == 0);

					   this.setFieldVisible( Ext.getCmp('search-tracking-number'), index < 2);
                       
					   var startDate = Ext.getCmp('search-start-date');
					  
					   if (index == 1 && startDate.getValue() == '' )
					   {  
                          startDate.setValue(new Date());
					   }
					   

				   }
				} //end listeners
			 },
		     {
				xtype:'textfield',
				id : 'search-tracking-number',
				fieldLabel: '单号'
			 },
			 {
				xtype:'textfield',
				id : 'sale-search-customer',
				fieldLabel : '客户'
			 },
			 {
				xtype: 'combo',
				id : 'sale-search-carrier',
				fieldLabel: '运输班组',
				store: carrier_ds,
				forceSelection : true,
				displayField: 'name',
				valueField:'id',
				editable: false,
				typeAhead: true,
				mode: 'local',
				value : '',
				triggerAction: 'all',
				selectOnFocus:true
			 },
			 {
				xtype: 'combo',
				id : 'warehousing-search-maker',
				fieldLabel: '生产班组',
				store: maker_ds,
				forceSelection : true,
				displayField: 'name',
				valueField:'id',
				editable: false,
				typeAhead: true,
				mode: 'local',
				value : '',
				triggerAction: 'all',
				selectOnFocus:true
			 },
			 {
				xtype: 'combo',
				id : 'sale-search-saler',
				fieldLabel: '销售员',
				store: salesman_ds,
				forceSelection : true,
				displayField: 'name',
				valueField:'id',
				editable: false,
				typeAhead: true,
				mode: 'local',
				value: '',
				triggerAction: 'all',
				selectOnFocus:true
			 },
		     {
				xtype:'datefield',
				id: 'search-start-date',
				fieldLabel:'起始日期',
				format:'Y-n-j' //, value: new Date() 
              }, 
			 {
				xtype:'datefield',
				id: 'search-end-date',
				fieldLabel:'截止日期',
			    format:'Y-n-j'
             },
			 {  xtype:'checkboxgroup',
				fieldLabel: '状态',
				id: 'sale-search-state',
				columns:1,
				items: [
				    {
						id: 'state-draft',
						name: 'sale_state',
						boxLabel: '登记单',
						inputValue: 'draft',
                        checked: true
					},
				    {
						id: 'state-in_transit',
						name: 'sale_state',
						boxLabel: '运送中',
						inputValue: 'in_transit',
						checked: true
					},
                     {
						id: 'state-prepare_for_payment',
						name: 'sale_state',
						boxLabel: '待支付',
						inputValue: 'prepare_for_payment'
					},
                     {
						id: 'state-close',
						name: 'sale_state',
						boxLabel: '完成',
						inputValue: 'close'
					}
				]
			 }
		    
		],
		buttons: [
			 {  text:'查询', width: 70,  handler: function(){
						   var query = new QueryDto();
						   var tn = Ext.getCmp('search-tracking-number');
						   if (tn.getValue()!=''){
							   query.trackingNumber = tn.getValue();
						   }
						   
						   var customer = Ext.getCmp('sale-search-customer');
						   if (customer.getValue()!=''){
							   query.customerName = customer.getValue();
						   }
						   
						   var carrier = Ext.getCmp('sale-search-carrier');
						   if (carrier.getValue() > 0){
							   query.carrier = carrier.getValue();
						   }

                           var maker = Ext.getCmp('warehousing-search-maker');
						   if (maker.getValue() > 0) {
							   query.maker = maker.getValue();
						   }

						   var saler = Ext.getCmp('sale-search-saler');
						   if (saler.getValue() > 0){
							   query.salesman = saler.getValue();
						   }

						   var startdate = Ext.getCmp('search-start-date');
						   
						   if (startdate.getRawValue() != ''){
							   query.startDate = startdate.getRawValue();
						   }

						   var enddate = Ext.getCmp('search-end-date');
						   if (enddate.getRawValue() != ''){
							   query.endDate = enddate.getRawValue();
						   }
						   
						   var states = new Array();
						   if (Ext.getCmp('state-draft').checked){
							  states.push('draft');
						   }
						   if (Ext.getCmp('state-in_transit').checked){
							  states.push('in_transit');
						   }
						   if (Ext.getCmp('state-prepare_for_payment').checked){
							  states.push('prepare_for_payment');
						   }
						   if (Ext.getCmp('state-close').checked){
							  states.push('close');
						   }
						   query.states = states;

                           if (query.startDate == null) {
							   query.startDate = '';
                           }

						   if (query.endDate == null)  {
							   query.endDate = '';
						   }
                           var query_type = Ext.getCmp('search-type').getValue();
						   if (query_type == '销售单'){
                               mainPanel.setActiveTab('sales-grid');
							   Ext.getCmp('sales-grid').setQuery(query);
						   }else if (query_type == '生产单'){
							   mainPanel.setActiveTab('product-in-grid');
							   Ext.getCmp('product-in-grid').setQuery(query);
						   }else if (query_type == '货运单') {
							   if (query.carrier == null){
                                  alert('你必须选择一个运输班组。');
								  return;
							   }
							  
							   if (query.startDate == '' || query.endDate =='') {
                                   alert('必须填写起止日期.');
								   return;
                               }
							   var carriage_store = new Ext.data.GroupingStore({
									sortInfo: {field: 'id', direction: 'ASC'},
									groupField: 'summary',
									data: [],
									reader: new Ext.data.JsonReader({
										idProperty: 'id',
										fields: [
										   {name: 'summary', type: 'string'},
										   {name: 'location.name', type:'string'},						   
										   {name: 'product.name', type:'string'},
										   {name: 'amount', type:'int'},
										   {name: 'freightPrice', type:'float'},
										   {name: 'freightFee', type:'float'},
										   {name: 'id', type:'int'}
									  ]})
							   });
								var carriageView = new Ext.grid.GroupingView({
									forceFit:true,
									showGroupName: false,
									enableNoGroups:false,
									enableGroupingMenu:false,
									hideGroupedColumn: true,
									startCollapsed:true //默认展开
								 });
							  // dwr.engine.setAsync(false); 
							   SaleManager.findCarriageItems(query.carrier, query.startDate, query.endDate, function(data){
							       carriage_store.loadData(data);
								   
								   carriage_report_win.setTitle(carriage_report_win.title + carriage_store.sum('freightFee'));
							   });
							   //dwr.engine.setAsync(true);
                                var carriage_report_win = new Ext.Window({
										    constrain : true,
											layout : 'fit',
											width : 550,
											title: '货运单查询-总运费:',
											closeAction : 'close',
											height : 500,
											resizable : false,
											shadow : true,
											modal : true,
											closable : true,
											border : false,										
											items:[

											{
												xtype:'grid',
												border: false,
												id: 'carriage-report-grid',
												//layout:'fit',
												enableHdMenu: false,
											    view: carriageView,
												store: carriage_store,
												plugins : [new Ext.ux.grid.GroupSummary()],
												columns: [
												   //new Ext.grid.RowNumberer(),
												   {header: '', dataIndex : 'summary', width: 0},
												   {header: '仓库位置', dataIndex : 'location.name', width : 70},
												   {header: '产品', dataIndex : 'product.name', width : 135},
												   {header: '数量', dataIndex : 'amount', width: 70, summaryType: 'sum'},
												   {header: '运输单价', dataIndex: 'freightPrice', width: 70},
												   {header: '运费', dataIndex: 'freightFee', summaryType: 'sum'}												   
												],
												tbar: [ { text:'打印', handler: function(){
												
												      printGrid(Ext.getCmp('carriage-report-grid'),'货运单', 
													   '运输班组:' + carrier.getRawValue(), '运费合计:' + carriage_store.sum('freightFee'));
												   }

												}, { text:'关闭', handler: function(){ 
													carriage_report_win.close(); 
													}
												}]
											  }											
											]
										 }).show();

						   
						   }else if (query_type == '产品销售统计'){
						      // mainPanel.loadModule('modules/productsalesummary.js', 'productsalesummary');
                               if (query.startDate == '' || query.endDate == '')
                               {
                                   alert('必须填写起止日期.');
								   return;
                               }
                              
							   var  product_sale_ds = new Ext.data.JsonStore({
									fields: [ 'productName', 'amount', 'sum', 'avaragePrice' ]
								});
							   SaleManager.getSaleSummaryReport(query.startDate, query.endDate, function(data){
							       product_sale_ds.loadData(data);
							   });
                                var sale_summary_win = new Ext.Window({
										    constrain : true,
											layout : 'fit',
											width : 400,
											title: '产品销售统计',
											closeAction : 'close',
											height : 400,
											resizable : false,
											shadow : true,
											modal : true,
											closable : true,
											border : false,										
											items:[

											{
												xtype:'grid',
												border: false,
												layout:'fit',
												enableHdMenu: false,
												store: product_sale_ds,
												columns: [
												   new Ext.grid.RowNumberer(),
												   {header: '产品', dataIndex : 'productName', sortable:true, width: 120},
												   {header: '总数量', dataIndex : 'amount', width : 80},
												   {header: '总金额', dataIndex : 'sum', width : 80},
												   {header: '平均单价', dataIndex : 'avaragePrice', width: 80}					
												]
											  }											
											]
										 }).show();

						   }
					   }
		        
		     }
			
		]
			                    	
    });


};
//指明NavPanel的父类
avatar.security.framework.MenuTreePanel=Ext.extend(MenuTreePanel, Ext.FormPanel, {
   // navPanelText:'检索'    
});


NavPanel = function() {

    // 显式调用父类构造器    
   NavPanel.superclass.constructor.call(this, {
        id:'nav-panel',
        region:'west',
        layout:'border',
        margins:'0 0 5 5',
        cmargins:'0 5 5 5',
        split:true,
        width: 175,
        minSize: 175,
        maxSize: 350,
        minHeight:600,
        collapsible: true,
        collapseMode:'mini',
        items:[ new MenuTreePanel()	]
    });
};
avatar.security.framework.NavPanel = Ext.extend(NavPanel, Ext.Panel, {
    
});


MainPanel = function() {
    // 显式调用父类构造器    
    MainPanel.superclass.constructor.call(this, {
        id:'main-tabs',
        region:'center',
        margins:'0 0 5 0',
        enableTabScroll : true,
        minTabWidth     : 75,
        activeTab:0,
        plugins: new Ext.ux.TabCloseMenu()
      //  items:[{
      //      title: this.centerPanelText,
      //      autoScroll:true
      //  }]

    });
	 dwr.engine.setAsync(false);
     this.loadModule('modules/sales.js', 'sales');
     dwr.engine.setAsync(true);

	 this.loadModule('modules/productcheckin.js', 'productcheckin');

	 
	

};

avatar.security.framework.MainPanel=Ext.extend(MainPanel, Ext.TabPanel, {

    loadModule : function(href,tabId){
	    var tab;
	    if(!(tab = this.getItem(tabId))){

			Ext.Ajax.request({   
				method:'GET',
				url: href,   
				scope: this,   
				success: function(response){
					 var module = eval(response.responseText);
                     new module(tab);  
				}
			});
        
	    }  else 
		    this.setActiveTab(tab);

    }
});



Ext.onReady(function(){
    var headerPanel = new avatar.security.framework.HeaderPanel();
    var navPanel = new avatar.security.framework.NavPanel();
    mainPanel = new avatar.security.framework.MainPanel();

    avatar.module = function(){
	    this.tabpanel = mainPanel;
	    this.init();
    }; 
    var viewport = new Ext.Viewport({
        layout:'border',
        items:[
            headerPanel,
            navPanel,
            mainPanel
        ]
    });
   Ext.getCmp('search-type').fireEvent('select', null , null , 0);
   Ext.get('x-loading-mask').hide();
   Ext.get('x-loading-panel').hide();
   
});
</script>
<script type="text/javascript" src="js-lib/ext-ux-js/locale/avatar-base-lang-zh_CN.js"></script>

<div id="header"></div>

<script>
//Ext.util.CSS.swapStyleSheet('theme', 'js-lib/ext-ux-js/resources/css/xtheme-gray-extend.css');
</script>

</body>
</html>